<!--  -->
<template>
  <div class="">
    <crumb  title="首页" title2="角色管理" title3="角色列表"></crumb >
    <el-card>
      <el-row :gutter="20">
        <el-col :span="3">
          <el-button type="primary" @click="dialogVisible1 = true">添加角色</el-button>
        </el-col>
      </el-row>

      <template>
        <el-table
          ref="multipleTable"
          :data="tableData"
          tooltip-effect="dark"
          style="width: 100%"
        >
          <el-table-column type="expand">
            <template slot-scope="props">
                <el-row class="styed" :class="index==0?'':'dptop'" v-for="(tag,index) in props.row.children" :key="tag.name">
                  <el-col :span="5" >
                    <el-tag  closable @close="removeRight(props.row,tag.id)">
                      {{ tag.authName }}
                    </el-tag>
                  </el-col>
                  <el-col :span="19">
                    <el-row  v-for="tag1 in tag.children" :key="tag1.name" class="styed">
                      <el-col :span="8" >
                        <el-tag closable  type="success" @close="removeRight(props.row,tag1.id)"> {{ tag1.authName }}</el-tag>
                       </el-col>
                       <el-col :span="16" >
                        <el-tag closable v-for="tag2 in tag1.children" type="warning" @close="removeRight(props.row,tag2.id)" :key="tag2.name"> {{ tag2.authName }}</el-tag>
                       </el-col>
                    </el-row>
                  </el-col>
                </el-row>
            </template>
          </el-table-column>
          <el-table-column prop="id" label="编号"> </el-table-column>
          <el-table-column prop="roleName" label="角色名称"> </el-table-column>
          <el-table-column prop="roleDesc" label="角色描述"> </el-table-column>
          <el-table-column label="操作">
            <template slot-scope="scope">
              <el-button size="mini" type="primary" @click="handleUpate(scope.row)"
                >编辑
              </el-button>
              <el-button size="mini" type="danger" @click="handleDelete(scope.row)"
                >删除
              </el-button>
              <el-button size="mini" type="warning" @click="rolesup(scope.row)"
                >权限
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </template>
    </el-card>
    <el-dialog
      title="分配权限"
      :visible.sync="dialogVisible"
      width="30%"
      :before-close="handleClose"
    >
      <span>
        <el-tree
          ref="treeref"
          :data="data"
          show-checkbox
          node-key="id"
          :default-checked-keys="defkes"
          :props="defaultProps"
          default-expand-all="true"
        >
        </el-tree>
      </span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="roleadd">确 定</el-button>
      </span>
    </el-dialog>

    <el-dialog
      title="添加"
      :visible.sync="dialogVisible1"
      width="50%"
      :before-close="handleClose1"
    >
      <el-form
        :model="ruleForm"
        :rules="rules"
        ref="ruleForm1"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="ruleForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="ruleForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="handleClose1">取 消</el-button>
        <el-button type="primary" @click="add">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog
      title="编辑"
      :visible.sync="dialogVisible2"
      width="50%"
      :before-close="handleClose2"
    >
      <el-form
        :model="ruleForm2"
        :rules="rules"
        ref="ruleForm2"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="ruleForm2.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="ruleForm2.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="handleClose2">取 消</el-button>
        <el-button type="primary" @click="updataadd">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
//这里可以导入其他文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）
//例如：import 《组件名称》 from '《组件路径》';

export default {
  //import引入的组件需要注入到对象中才能使用
  components: {},
  data() {
    //这里存放数据
    return {
      defkes: [],
      kesid: 0,
      updateid: 0,
      tableData: [],
      dialogVisible: false,
      dialogVisible1: false,
      dialogVisible2: false,
      data: [],
      defaultProps: {
        children: "children",
        label: "authName",
      },
      ruleForm: {
        roleName: "",
        roleDesc: "",
      },
      ruleForm2: {
        roleName: "",
        roleDesc: "",
      },
      rules: {
        username: [
          { required: true, message: "请输入名称", trigger: "blur" },
          { min: 3, max: 10, message: "长度在 3 到 10 个字符", trigger: "blur" },
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          { min: 6, max: 15, message: "长度在 6到 15 个字符", trigger: "blur" },
        ],
      },
    };
  },
  //监听属性 类似于data概念
  computed: {},
  //监控data中的数据变化
  watch: {},
  //方法集合
  methods: {
  async  removeRight(role,id){
      const confirmResult =await this.$confirm(' 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });          
        });
        // console.log(confirmResult);
        if(confirmResult=='confirm'){
          const { data: res } = await this.myaxios.delete(
        `roles/${role.id}/rights/${id}`
      );
      role.children=res.data
        }
    },
    handleUpate(row) {
      this.updateid = row.id;
      this.ruleForm2 = row;
      this.dialogVisible2 = true;
    },
    async updataadd() {
      const { data: res } = await this.myaxios.put(
        `roles/${this.updateid}`,
        this.ruleForm2
      );
      if (res.meta.status !== 200) {
        this.$message.error("编辑用户失败！");
      } else {
        this.$message.success("编辑用户成功！");
      }
      this.handleClose2();
      this.getData();
    },
    async handleDelete(row) {
      const { data: res } = await this.myaxios.delete(`roles/${row.id}`);
      if (res.meta.status !== 200) {
        this.$message.error("删除用户失败！");
      } else {
        this.$message.success("删除用户成功！");
        this.getData();
      }
    },
    handleClose1() {
      this.dialogVisible1 = false;
      this.$refs.ruleForm1.resetFields();
    },
    handleClose2() {
      this.dialogVisible2 = false;
      this.$refs.ruleForm2.resetFields();
    },
    async add() {
      this.$refs.ruleForm1.validate(async (valid) => {
        if (!valid) return;
        const { data: res } = await this.myaxios.post("roles", this.ruleForm);
        if (res.meta.status !== 201) {
          this.$message.error("添加用户失败！");
        }
        if (res.meta.status == 400) {
          this.$message.error(res.meta.message);
        }
        this.$message.success("添加用户成功!");
        this.handleClose1();
        this.getData();
      });
      const { data: res } = await this.myaxios.post("roles");
    },
    async getData() {
      const { data: res } = await this.myaxios.get("roles");
      this.tableData = res.data;
      console.log(this.tableData);
      this.$message({
          message: '获取数据成功',
          type: 'success'
        });
    },
    handleClose() {
      this.dialogVisible = false;
      this.defkes = [];
    },
    async rolesup(row) {
      this.kesid = row.id;
      this.defkes = [];
      this.dialogVisible = true;
      const { data: res } = await this.myaxios.get(`rights/tree`);
      console.log(res);
      this.data = res.data;
      for (var i = 0; i < row.children.length; i++) {
        var leve1 = row.children[i];
        for (var j = 0; j < leve1.children.length; j++) {
          var leve2 = leve1.children[j];
          for (var k = 0; k < leve2.children.length; k++) {
            var leve3 = leve2.children[k];
            this.defkes.push(leve3.id);
          }
        }
      }
    },
    async roleadd() {
      const keys = [
        ...this.$refs.treeref.getCheckedKeys(),
        ...this.$refs.treeref.getHalfCheckedKeys(),
      ];
      var idStr = keys.join(",");
      const { data: res } = await this.myaxios.post(`roles/${this.kesid}/rights`, {
        rids: idStr,
      });
      if (res.meta.status !== 200) {
        return this.$message.error("失败！");
      }
      this.$message.success("成功!");
      this.getData();
      this.handleClose();
    },
  },
  //生命周期 - 创建完成（可以访问当前this实例）
  created() {
    this.getData();
  },
  //生命周期 - 挂载完成（可以访问DOM元素）
  mounted() {},
  beforeCreate() {}, //生命周期 - 创建之前
  beforeMount() {}, //生命周期 - 挂载之前
  beforeUpdate() {}, //生命周期 - 更新之前
  updated() {}, //生命周期 - 更新之后
  beforeDestroy() {}, //生命周期 - 销毁之前
  destroyed() {}, //生命周期 - 销毁完成
  activated() {}, //如果页面有keep-alive缓存功能，这个函数会触发
};
</script>
<style scoped>
.el-tag {
  margin: 5px;
}
.styed{
  display:flex;
 align-items: center;
  }
.dptop{
  border-top:1px solid #e2e2e2;
}
</style>
